//
//  ShoppingPromotion.m
//  mbstore
//
//  Created by huangyi on 14-3-24.
//  Copyright (c) 2014年 huangyi. All rights reserved.
//

#import "ShoppingPromotion.h"

@interface ShoppingPromotion ()

@property(nonatomic,strong)NSArray *promoList;

@end

@implementation ShoppingPromotion

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        self.modalPresentationStyle=UIModalPresentationFormSheet;
        self.modalTransitionStyle=UIModalTransitionStyleFlipHorizontal;

    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self.vieContaniter.layer setBorderWidth:1];
    [self.vieContaniter.layer setBorderColor:[UIColor lightGrayColor].CGColor];
    // Do any additional setup after loading the view from its nib.
    self.title=@"门店促销设置";

   
  
    UIButton *set=[UIButton buttonWithType:UIButtonTypeCustom];
//    [set setTitle:@"设置" forState:UIControlStateNormal];
     [set setTitle:@"确定" forState:UIControlStateNormal];
    [set sizeToFit];
    [set addTarget:self action:@selector(onSetClick:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItems=@[set.barButtonItem];
    self.tableView.rowHeight=60;
}
-(void)viewWillAppear:(BOOL)animated{
    MainApp *app=[MainApp mainApp];
    self.promoList=[app requestPromotion];
    [self.tableView reloadData];
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)onSetClick:(id)sender{
    [self.navigationController dismissViewControllerAnimated:YES completion:nil];
    NSMutableArray *array=[NSMutableArray array];
    for (NSMutableDictionary *item in self.promoList) {
        NSNumber *selected=item[@"IsSelected"];
        if ([selected boolValue]) {
            NSMutableDictionary *dict=[NSMutableDictionary dictionary];
            dict[@"IsSelected"]=@1;
            dict[@"PromotionRuleid"]=item[@"PromotionRuleid"];
            [array addObject:dict];
        }
    }
    UIButton *button=sender;
    [button runTask:^{
        [AppUI setPromotion:array];
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.navigationController popViewControllerAnimated:YES];
        });
    }];
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.promoList.count;
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSString *identifier=@"promo";
    UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:identifier];
    if (!cell) {
        cell=[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:identifier];
    }
    else
    {   // 删除cell中的子对象,刷新覆盖问题。
        while ([cell.contentView.subviews lastObject] != nil)
        {
            [(UIView*)[cell.contentView.subviews lastObject] removeFromSuperview];
        }
    }
    NSMutableDictionary *item=[self.promoList objectAtIndex:indexPath.row];
     NSNumber *selected=item[@"IsSelected"];
    UIButton *btnSelect=[[UIButton alloc]initWithFrame:CGRectMake(30, 20, 20, 20)];
    if ([selected boolValue]) {
        [btnSelect setImage:[UIImage imageNamed:@"selectRed"] forState:UIControlStateNormal];
//       btnSelect.backgroundColor=[UIColor redColor];
    }else{
         [btnSelect setImage:[UIImage imageNamed:@"selectGry"] forState:UIControlStateNormal];
//        btnSelect.backgroundColor=[UIColor blueColor];
    }
    
    [cell.contentView addSubview:btnSelect];
    
//    for (int i=0; i<4; i++) {
        UILabel *labNum=[[UILabel alloc]initWithFrame:CGRectMake(93, 0, 75, 60)];
        labNum.text=item[@"PromotionRuleid"];
    labNum.numberOfLines=0;
    labNum.font=[UIFont systemFontOfSize:13];
        [cell.contentView addSubview:labNum];
//    }
    
    UILabel *labActivity=[[UILabel alloc]initWithFrame:CGRectMake(180, 0, 166, 60)];
    labActivity.text=item[@"PromotionRulename"];
    labActivity.numberOfLines=0;
     labActivity.font=[UIFont systemFontOfSize:13];
    [cell.contentView addSubview:labActivity];
    
    UILabel *labStartTime=[[UILabel alloc]initWithFrame:CGRectMake(346, 0, 77, 60)];
    labStartTime.text=[self parseDate:item[@"ValidBgDate"]];
     labStartTime.font=[UIFont systemFontOfSize:13];
    [cell.contentView addSubview:labStartTime];
    
    UILabel *labEndTime=[[UILabel alloc]initWithFrame:CGRectMake(441, 0, 77, 60)];
    labEndTime.text=[self parseDate:item[@"ValidDate"]];
     labEndTime.font=[UIFont systemFontOfSize:13];
    [cell.contentView addSubview:labEndTime];
    
    
//    cell.textLabel.text=item[@"PromotionRulename"];
//    NSString *begin=[self parseDate:item[@"ValidBgDate"]];
//    NSString *end=[self parseDate:item[@"ValidDate"]];
//    cell.detailTextLabel.text=[NSString stringWithFormat:@"开始时间：%@  结束时间：%@",begin,end];
//    NSNumber *selected=item[@"IsSelected"];
//    if ([selected boolValue]) {
//        cell.accessoryType=UITableViewCellAccessoryCheckmark;
//    }else{
//        cell.accessoryType=UITableViewCellAccessoryNone;
//    }
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    UITableViewCell *cell=[tableView cellForRowAtIndexPath:indexPath];

    NSMutableDictionary *item=[self.promoList objectAtIndex:indexPath.row];
    NSNumber *selected=item[@"IsSelected"];
    if ([selected boolValue]) {
        [item setValue:@0 forKeyPath:@"IsSelected"];
//        cell.accessoryType=UITableViewCellAccessoryNone;
    }else{
        [item setValue:@1 forKeyPath:@"IsSelected"];
//        cell.accessoryType=UITableViewCellAccessoryCheckmark;
    }
    [self.tableView reloadData];
}

#warning TODO: 时间字符串格式化
-(NSString*)parseDate:(NSString*)dateString{
    NSString *str=[dateString substringWithRange:NSMakeRange(6, 10)];
    int ts=[str intValue];
    ts=ts-60*60*8;//+8时区
    NSDate *date=[NSDate dateWithTimeIntervalSince1970:ts];
    NSDateFormatter *formatter=[[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd"];
    return [formatter stringFromDate:date];
}

@end
